<?php
/**
 * 权限相关
 */

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\models\Access;
use app\controllers\AdminController;
use yii\helpers\Json;

class AccessController extends AdminController
{
    /**
     * 功能列表
     */
    public function actionIndex()
    {
        $accessList = Access::find()->asArray()->all();
        Access::formatList($accessList);
        return $this->render('list', ['list' => $accessList]);
    }

    /**
     * 添加,编辑页面
     */
    public function actionShow()
    {
        $id = $this->get('id', '');

        $info = [];
        if ($id) {
            $info = Access::find()->where(['id' => $id])->asArray()->one();
            if ($info) {
                $urls = json_decode($info['urls'], true);
                $info['urls'] = implode("\r\n", $urls);
            }
        }

        $data = [
            'info' => $info,
            'menu' => Access::getFirstLevelMenu(),
        ];
        return $this->render('set', $data);
    }

    /**
     * 提交添加,编辑
     */
    public function actionSet()
    {
        $request = Yii::$app->request;
        if ($request->isAjax) {
            $id = $this->post('id', '');
            $title = $this->post('title', '');
            $urls = $this->post('urls', );
            $desc = $this->post('desc', '');
            $parent_id = $this->post('parent_id', 0);
            $is_menu = $this->post('is_menu', 0);

            // 参数有效性验证
            if (empty($title)) {
                $this->errorJson('标题不能为空');
            }

            $urls = explode("\n",$urls);
            if( !$urls ){
                $this->errorJson('请输入合法的Url');
            }

            $time = time();
            $accessInfo = Access::find()->where(['id' => $id])->one();
            if ($accessInfo) {
                $accessModel = $accessInfo;
            } else {
                $accessModel = new Access();
                $accessModel->status = 1;
                $accessModel->create_at = $time;
            }

            $accessModel->title = $title;
            $accessModel->urls = json_encode($urls, JSON_UNESCAPED_UNICODE);
            $accessModel->desc = $desc;
            $accessModel->parent_id = $parent_id;
            $accessModel->is_menu = $is_menu;
            $accessModel->update_at = $time;
            $accessModel->save(0);

            $this->okJson();
        }
    }

    /**
     * 删除权限
     */
    public function actionDel()
    {
        $id = $this->post('id', '');
        if (!$id) {
            $this->errorJson('参数错误');
        }

        $info = Access::find()->where(['id' => $id])->one();
        if (!$info) {
            $this->errorJson('信息不存在');
        }

        $info->status = 0;
        $info->save(0);

        $this->okJson();
    }
}